"use strict";
define(["commonUI","getTime","laydate","echarts", "template","global","select2", "datatables","ztreeExhide"], function (
    commonUI, getTime,laydate, echarts, template,global
) {
    var project = null;
    var user = null;
    var projectIds = []
    var chart1,chart2,chart3,chart4;
    var map = new Map();
    var letter = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
    var app = {
        init: function () {
            if(!global.existCurrProject()){
                return;
            }
            project = global.getCurrProject();
            user = global.getLoginUser();
            this.initText();
            this.eventBind();
            // getTime.resize();
            getTime.getNowDate();
            getTime.getTimeInfo();
            this.initProjectList()
            this.initChart1();
            this.initChart2();
            this.initChart3();
            this.initChart4();
        },
        /**
        * 渲染文字内容
        */
        initText: function() {
            //用户名显示
            $(".name").text(user.userName)
        },
        initChart1: function () {
            if (chart1) {
                chart1.dispose();
            }
            if(projectIds.length<=0){
                return;
            }
            var type = $("#timeType1 li.active").attr("type");
            var timeLength = 0;
            if(type==0){
                timeLength=10;
            }else if(type==1){
                timeLength=10
            }else if(type==2){
                timeLength=10
            }
            global.get("/web/dc/machine_group_efficiency?projectIds="+projectIds+"&timeMode="+type+"&timeLength="+timeLength,response=>{
                if(response.success){
                    var xArr = []
                    var dates = response.data.dates;
                    var machineGroups = response.data.machineGroups;
                    for(var i=0;i<dates.length;i++){
                        if(type==0){
                            xArr.push(dates[i].substring(11,13)+"时");
                        }else if(type==1){
                            xArr.push(dates[i].substring(8,10)+"日");
                        }else if(type==2){
                            xArr.push(dates[i].substring(5,7)+"月");
                        }
                    }
                    var legend_data = [];
                    var series = []
                    for(var i=0;i<machineGroups.length;i++){
                        var name = machineGroups[i].name;
                        name = name.substring(0,name.length-5)
                        legend_data.push(map.get(name));
                        var d = [];
                        machineGroups[i].efficiency.forEach(item=>{
                            if(item!=null){
                                d.push(item)
                            }else{
                                d.push(0);
                            }
                        });
                        series.push({
                            name: map.get(name),
                            type: "line",
                            smooth: true,
                            lineStyle: {
                                // color:'rgb(48,160,238)',
                                width:1
                            },
                            // areaStyle: {
                            //     normal: {
                            //         color: {
                            //             type: 'linear',
                            //             x: 0,
                            //             y: 0,
                            //             x2: 0,
                            //             y2: 1,
                            //             colorStops: [{
                            //                 offset: 0, 
                            //                 color: 'rgb(48,160,238)' // 0% 处的颜色
                            //             }, {
                            //                 offset: 1,
                            //                 color: 'rgba(48,160,238, 0)' // 100% 处的颜色
                            //             }],
                            //             globalCoord: false // 缺省为 false
                            //         }
                            //     }
                            // },
                            data:d
                        })
                    }
                    
                    var option = {
                        color:['#30a0ee','#df5d60','#edd719','#19edaa','#764ddf'],
                        tooltip: {
                            trigger: "axis",
                            backgroundColor:'rgba(0,0,0,0.5)',
                            borderWidth:0,
                            textStyle:{
                                color:'#ffffff'
                            },
                            padding:[10,50,10,15],
                            // formatter: month + '月' + '{b}日<br />{a0}: {c0}单位<br />{a1}: {c1}单位<br />{a2}: {c2}单位<br />{a3}: {c3}单位<br />{a4}: {c4}单位<br />'
                        },
                        legend: {
                            data: legend_data,
                            right: 'center',
                            width:'100%',
                            top: 0,
                            selectedMode: false,
                            textStyle: {
                                color: "#94d3ff"
                            },
                            icon:'circle'
                        },
                        grid: {
                            left: 24,
                            right: 24,
                            bottom: 0,
                            top: 36,
                            containLabel: true
                        },
                        xAxis: [
                            {
                                type: "category",
                                boundaryGap: false,
                                axisTick: {
                                    show: false
                                },
                                axisLine: {
                                    lineStyle: {
                                        color: "#ffffff"
                                    }
                                },
                                axisLabel: {
                                    color: "#94d3ff"
                                },
                                data: xArr
                            }
                        ],
                        yAxis: [
                            {
                                name: "COP",
                                type: "value",
                                splitNumber: 2,
                                nameTextStyle: {
                                    color: "#94d3ff"
                                },
                                axisTick: {
                                    show: false
                                },
                                axisLine: {
                                    show: false
                                },
                                axisLabel: {
                                    color: "#94d3ff"
                                },
                                splitLine: {
                                    lineStyle: {
                                        type: "dashed",
                                        color: "#94d3ff",
                                        opacity: 0.5
                                    }
                                }
                            }
                        ],
                        series: series,
                    };
                    chart1 = echarts.init(document.getElementById("chart1"));
                    chart1.setOption(option);
                }else{
                    alert(response.message)
                }
            });
            
        },
        initChart2: function () {
            if (chart2) {
                chart2.dispose();
            }
            if(projectIds.length<=0){
                return;
            }
            var type = $("#timeType2 li.active").attr("type");
            var timeLength = 0;
            if(type==0){
                timeLength=10;
            }else if(type==1){
                timeLength=10
            }else if(type==2){
                timeLength=10
            }
            global.get("/web/dc/system_efficiency?projectIds="+projectIds+"&timeMode="+type+"&timeLength="+timeLength,response=>{
                if(response.success){
                    var xArr = []
                    var dates = response.data.dates;
                    for(var i=0;i<dates.length;i++){
                        if(type==0){
                            xArr.push(dates[i].substring(11,13)+"时");
                        }else if(type==1){
                            xArr.push(dates[i].substring(8,10)+"日");
                        }else if(type==2){
                            xArr.push(dates[i].substring(5,7)+"月");
                        }
                    }
                    var series = []
                    var legend_data = [];
                    var efficiencies = response.data.efficiencies
                    for(var i=0;i<efficiencies.length;i++){
                        var name = efficiencies[i].name;
                        name = name.substring(0,name.length-5)
                        legend_data.push(map.get(name));
                        var d = [];
                        efficiencies[i].efficiency.forEach(item=>{
                            if(item!=null){
                                d.push(item)
                            }else{
                                d.push(0);
                            }
                        });
                        series.push({
                            name: map.get(name),
                            type: "line",
                            smooth: true,
                            lineStyle: {
                                // color:'rgb(48,160,238)',
                                width:1
                            },
                            // areaStyle: {
                            //     normal: {
                            //         color: {
                            //             type: 'linear',
                            //             x: 0,
                            //             y: 0,
                            //             x2: 0,
                            //             y2: 1,
                            //             colorStops: [{
                            //                 offset: 0, color: 'rgb(48,160,238)' // 0% 处的颜色
                            //             }, {
                            //                 offset: 1, color: 'rgba(48,160,238, 0)' // 100% 处的颜色
                            //             }],
                            //             globalCoord: false // 缺省为 false
                            //         }
                            //     }
                            // },
                            data:d
                        })
                    }
                    var option = {
                        color:['#30a0ee','#df5d60'],
                        tooltip: {
                            trigger: "axis",
                            backgroundColor:'rgba(0,0,0,0.5)',
                            borderWidth:0,
                            textStyle:{
                                color:'#ffffff'
                            },
                            padding:[10,50,10,15],
                            // formatter: month + '月' + '{b}日<br />{a0}: {c0}单位<br />{a1}: {c1}单位<br />{a2}: {c2}单位<br />{a3}: {c3}单位<br />{a4}: {c4}单位<br />'
                        },
                        legend: {
                            data: legend_data,
                            right: 'center',
                            width:'100%',
                            top: 0,
                            selectedMode: false,
                            textStyle: {
                                color: "#94d3ff"
                            },
                            icon:'circle'
                        },
                        grid: {
                            left: 24,
                            right: 24,
                            bottom: 0,
                            top: 36,
                            containLabel: true
                        },
                        xAxis: [
                            {
                                type: "category",
                                boundaryGap: false,
                                axisTick: {
                                    show: false
                                },
                                axisLine: {
                                    lineStyle: {
                                        color: "#ffffff"
                                    }
                                },
                                axisLabel: {
                                    color: "#94d3ff"
                                },
                                data: xArr
                            }
                        ],
                        yAxis: [
                            {
                                name: "COP",
                                type: "value",
                                splitNumber: 2,
                                nameTextStyle: {
                                    color: "#94d3ff"
                                },
                                axisTick: {
                                    show: false
                                },
                                axisLine: {
                                    show: false
                                },
                                axisLabel: {
                                    color: "#94d3ff"
                                },
                                splitLine: {
                                    lineStyle: {
                                        type: "dashed",
                                        color: "#94d3ff",
                                        opacity: 0.5
                                    }
                                }
                            }
                        ],
                        series:series
                    };       
                    chart2 = echarts.init(document.getElementById("chart2"));
                    chart2.setOption(option);
                }else{
                    alert(response.message)
                }
            })
        },
        initChart3: function () {
            if (chart3) {
                chart3.dispose();
            }
            if(projectIds.length<=0){
                return;
            }
            var type = $("#timeType3 li.active").attr("type");
            var timeLength = 0;
            if(type==0){
                timeLength=10;
            }else if(type==1){
                timeLength=10
            }else if(type==2){
                timeLength=10
            }
            global.get("/web/dc/soil_temperature?projectIds="+projectIds+"&timeMode="+type+"&timeLength="+timeLength,response=>{
                if(response.success){
                    var xArr = []
                    var legend_data = [];
                    var dates = response.data.dates;
                    
                    for(var i=0;i<dates.length;i++){
                        if(type==0){
                            xArr.push(dates[i].substring(11,13)+"时");
                        }else if(type==1){
                            xArr.push(dates[i].substring(8,10)+"日");
                        }else if(type==2){
                            xArr.push(dates[i].substring(5,7)+"月");
                        }
                    }
                    var legend_data = [];
                    var series = []
                    var temperatures = response.data.temperatures;
                    for(var i=0;i<temperatures.length;i++){
                        var name = temperatures[i].name;
                        name = name.substring(0,name.length-5)
                        legend_data.push(map.get(name));
                        var d = [];
                        temperatures[i].temperature.forEach(item=>{
                            if(item!=null){
                                d.push(item)
                            }else{
                                d.push(0);
                            }
                        });
                        series.push({
                            name: map.get(name),
                            type: "line",
                            smooth: true,
                            lineStyle: {
                                // color:'rgb(48,160,238)',
                                width:1
                            },
                            // areaStyle: {
                            //     normal: {
                            //         color: {
                            //             type: 'linear',
                            //             x: 0,
                            //             y: 0,
                            //             x2: 0,
                            //             y2: 1,
                            //             colorStops: [{
                            //                 offset: 0, color: 'rgb(48,160,238)' // 0% 处的颜色
                            //             }, {
                            //                 offset: 1, color: 'rgba(48,160,238, 0)' // 100% 处的颜色
                            //             }],
                            //             globalCoord: false // 缺省为 false
                            //         }
                            //     }
                            // },
                            data:d
                        })
                    }
                    var option = {
                        tooltip: {
                            trigger: "axis",
                            backgroundColor:'rgba(0,0,0,0.5)',
                            borderWidth:0,
                            textStyle:{
                                color:'#ffffff'
                            },
                            padding:[10,50,10,15],
                            // formatter: '{b}:00<br />{a}: {c}<br />'
                        },
                        legend: {
                            data: legend_data,
                            right: 'center',
                            top: 0,
                            selectedMode: false,
                            textStyle: {
                                color: "#94d3ff"
                            }
                        },
                        grid: {
                            left: 24,
                            right: 24,
                            bottom: 0,
                            top: 36,
                            containLabel: true
                        },
                        xAxis: [
                            {
                                type: "category",
                                boundaryGap: false,
                                axisTick: {
                                    show: false
                                },
                                axisLine: {
                                    lineStyle: {
                                        color: "#ffffff"
                                    }
                                },
                                axisLabel: {
                                    color: "#94d3ff"
                                },
                                data: xArr
                            }
                        ],
                        yAxis: [
                            {
                                name: "℃",
                                type: "value",
                                splitNumber: 2,
                                nameTextStyle: {
                                    color: "#94d3ff"
                                },
                                axisTick: {
                                    show: false
                                },
                                axisLine: {
                                    show: false
                                },
                                axisLabel: {
                                    color: "#94d3ff"
                                },
                                splitLine: {
                                    lineStyle: {
                                        type: "dashed",
                                        color: "#94d3ff",
                                        opacity: 0.5
                                    }
                                }
                            }
                        ],
                        series: series,
                        color: ["#b9d0ff", "#fddd99"]
                    };
                    chart3 = echarts.init(document.getElementById("chart3"));
                    chart3.setOption(option);
                }else{
                    alert(response.message)
                }
            });
        },
        initChart4: function () {
            if (chart4) {
                chart4.dispose();
            }
            if(projectIds.length<=0){
                return;
            }
            var type = $("#timeType4 li.active").attr("type");
            var timeLength = 0;
            if(type==0){
                timeLength=10;
            }else if(type==1){
                timeLength=10
            }else if(type==2){
                timeLength=10
            }
            global.get("/web/dc/pump_transmission_coefficient?projectIds="+projectIds+"&timeMode="+type+"&timeLength="+timeLength,response=>{
                if(response.success){
                    var xArr = []
                    var dates = response.data.dates;
                    for(var i=0;i<dates.length;i++){
                        if(type==0){
                            xArr.push(dates[i].substring(11,13)+"时");
                        }else if(type==1){
                            xArr.push(dates[i].substring(8,10)+"日");
                        }else if(type==2){
                            xArr.push(dates[i].substring(5,7)+"月");
                        }
                    }
                    var legend_data = [];
                    var series = []
                    var coefficients = response.data.coefficients;
                    for(var i=0;i<coefficients.length;i++){
                        var name = coefficients[i].name;
                        name = name.substring(0,name.length-9)
                        name = map.get(name) + coefficients[i].name.substring(coefficients[i].name.length-9,coefficients[i].name.length-4)
                        legend_data.push(name);
                        var d = [];
                        coefficients[i].coefficient.forEach(item=>{
                            if(item!=null){
                                d.push(item*100)
                            }else{
                                d.push(0);
                            }
                        });
                        series.push({
                            name: name,
                            type: "line",
                            smooth: true,
                            lineStyle: {
                                // color:'rgb(48,160,238)',
                                width:1
                            },
                            // areaStyle: {
                            //     normal: {
                            //         color: {
                            //             type: 'linear',
                            //             x: 0,
                            //             y: 0,
                            //             x2: 0,
                            //             y2: 1,
                            //             colorStops: [{
                            //                 offset: 0, color: 'rgb(48,160,238)' // 0% 处的颜色
                            //             }, {
                            //                 offset: 1, color: 'rgba(48,160,238, 0)' // 100% 处的颜色
                            //             }],
                            //             globalCoord: false // 缺省为 false
                            //         }
                            //     }
                            // },
                            data:d
                        })
                    }
                    var option = {
                        tooltip: {
                            trigger: "axis",
                            backgroundColor:'rgba(0,0,0,0.5)',
                            borderWidth:0,
                            textStyle:{
                                color:'#ffffff'
                            },
                            padding:[10,50,10,15],
                        },
                        legend: {
                            data: legend_data,
                            right: 24,
                            top: 0,
                            selectedMode: false,
                            textStyle: {
                                color: "#94d3ff"
                            }
                        },
                        grid: {
                            left: 24,
                            right: 24,
                            bottom: 0,
                            top: 36,
                            containLabel: true
                        },
                        xAxis: [
                            {
                                type: "category",
                                boundaryGap: false,
                                axisTick: {
                                    show: false
                                },
                                axisLine: {
                                    lineStyle: {
                                        color: "#ffffff"
                                    }
                                },
                                axisLabel: {
                                    color: "#94d3ff"
                                },
                                data: xArr
                            }
                        ],
                        yAxis: [
                            {
                                name: "%",
                                type: "value",
                                max: 100,
                                splitNumber: 2,
                                nameTextStyle: {
                                    color: "#94d3ff"
                                },
                                axisTick: {
                                    show: false
                                },
                                axisLine: {
                                    show: false
                                },
                                axisLabel: {
                                    color: "#94d3ff"
                                },
                                splitLine: {
                                    lineStyle: {
                                        type: "dashed",
                                        color: "#94d3ff",
                                        opacity: 0.5
                                    }
                                }
                            }
                        ],
                        series: series,
                        color: ["#b9d0ff", "#fddd99"]
                    };   
                    chart4 = echarts.init(document.getElementById("chart4"));
                    chart4.setOption(option);
                }else{
                    alert(response.message)
                }
            });
        },
        initProjectList: function () {
            var setting = {
                check: {
                    enable: false//checkbox
                },
                view: {
                    nameIsHTML: true, //允许name支持html                
                    selectedMulti: false,
                    showLine: false,
                    showIcon: false,
                },
                edit: {
                    enable: false,
                    editNameSelectAll: false
                },
                data: {
                    simpleData: {
                        enable: true
                    }
                },
                callback: {
                    onClick: onClick,
                }
            };
            global.get("/web/project/listByUser/",function(response){
                var projects = response.data.projects;
                var zNodes = []
                var id=0;
                for(var i=0;i<projects.length;i++){
                    var p = projects[i];
                    var item = {};
                    item.open = true;
                    
                    item.name= letter[id++] +'-'+ p.name;
                    map.set(p.name,letter[id-1])
                    item.id = p.id
                    if(p.id==project.id){
                        projectIds.push(project.id);
                    }
                    zNodes.push(item);
                }
                console.log(map)
                $(document).ready(function(){
                    var tree = $.fn.zTree.init($("#treeDemo_1"), setting, zNodes);
                    var nodes = tree.getNodes()
                    nodes.forEach(node=>{
                        if(node.id==project.id){
                            $("#"+node.tId).find(".node_name").css("color","rgba(232,222,21,0.5)");
                        }
                    })
                    fuzzySearch('treeDemo_1','#key',null,true); //初始化模糊搜索方法
                });
            },null,false,false);
            // 点击树节点事件
            function onClick(event, treeId, treeNode) {
                var nodeId = treeNode.id;
                var $this = $(event.target)
                if(projectIds.indexOf(nodeId)>-1){
                    projectIds.splice(projectIds.indexOf(nodeId),1);
                    if($this.hasClass("node_name")){
                        $this.css("color","#BDD2DF");
                    }else{
                        $this.find(".node_name").css("color","#BDD2DF")
                    }
                }else{
                    if(projectIds.length>=4){
                        Dialog.toast("一次选择最多支持选择4个项目进行对比", {"intent":"warn"});
                        return;
                    }
                    if($this.hasClass("node_name")){
                        $this.css("color","rgba(232,222,21,0.5)");
                    }else{
                        $this.find(".node_name").css("color","rgba(232,222,21,0.5)")
                    }
                    projectIds.push(treeNode.id)
                }
                app.initChart1();
                app.initChart2();
                app.initChart3();
                app.initChart4();
            }
            function fuzzySearch(zTreeId, searchField, isHighLight, isExpand){
                // 通过id获取树
                var zTreeObj = $.fn.zTree.getZTreeObj(zTreeId);
                if(!zTreeObj){
                    alter("fail to get ztree object");
                }
                // 通过name获取key
                var nameKey = zTreeObj.setting.data.key.name; 
                // 默认为true，仅在使用false时禁用highlight
                isHighLight = isHighLight===false?false:true;
                isExpand = isExpand?true:false; 
                // 使用高亮的情况下允许在node name中使用html
                zTreeObj.setting.view.nameIsHTML = isHighLight; 
            
                var metaChar = '[\\[\\]\\\\\^\\$\\.\\|\\?\\*\\+\\(\\)]'; 
                var rexMeta = new RegExp(metaChar, 'gi');
            
                // keyword过滤
                function ztreeFilter(zTreeObj,_keywords,callBackFunc) {
                    if(!_keywords){
                        // 默认为空
                        _keywords =''; 
                    }
            
                    // 找出匹配节点
                    function filterFunc(node) {
                        if(node && node.oldname && node.oldname.length>0){
                            node[nameKey] = node.oldname; 
                        }
                        zTreeObj.updateNode(node); 
                        if (_keywords.length == 0) {
                            // 如果keyword为空返回所有
                            zTreeObj.showNode(node);
                            zTreeObj.expandNode(node,isExpand);
                            return true;
                        }
                        //转换 node name and keywords 为小写
                        if (node[nameKey] && node[nameKey].toLowerCase().indexOf(_keywords.toLowerCase())!=-1) {
                            if(isHighLight){ 
                                var newKeywords = _keywords.replace(rexMeta,function(matchStr){
                                    return '\\' + matchStr;
                                });
                                node.oldname = node[nameKey]; //store the old name  
                                var rexGlobal = new RegExp(newKeywords, 'gi');
                                node[nameKey] = node.oldname.replace(rexGlobal, function(originalText){
                                    //高亮匹配的文字
                                    var highLightText =
                                        '<span style="color: #2D2F33;background-color: #BEDAFD;">'
                                        + originalText
                                        +'</span>';
                                    return     highLightText;                    
                                });
                                zTreeObj.updateNode(node); 
                            }
                            zTreeObj.showNode(node);
                            return true; 
                        }
            
                        zTreeObj.hideNode(node); 
                        return false; 
                    }
            
                    var nodesShow = zTreeObj.getNodesByFilter(filterFunc); 
                    processShowNodes(nodesShow, _keywords);
                }
                /**
                 * 节点展示前进行处理
                 */
                function processShowNodes(nodesShow,_keywords){
                    if(nodesShow && nodesShow.length>0){
                        if(_keywords.length>0){ 
                            $.each(nodesShow, function(n,obj){
                                var pathOfOne = obj.getPath();
                                if(pathOfOne && pathOfOne.length>0){ 
                                    for(var i=0;i<pathOfOne.length-1;i++){
                                        zTreeObj.showNode(pathOfOne[i]); 
                                        zTreeObj.expandNode(pathOfOne[i],true); 
                                    }
                                }
                            });    
                        }else{ 
                            // 显示所有节点当 _keywords 为空时
                            var rootNodes = zTreeObj.getNodesByParam('level','0');
                            $.each(rootNodes,function(n,obj){
                                zTreeObj.expandNode(obj,true);
                            });
                        }
                    }
                }
                //监听input改变事件
                $(searchField).bind('input propertychange', function() {
                    var _keywords = $(this).val();
                    searchNodeLazy(_keywords); 
                });
                var timeoutId = null;
                // input 改变后执行
                function searchNodeLazy(_keywords) {
                    if (timeoutId) { 
                        //终止前一个
                        clearTimeout(timeoutId);
                    }
                    timeoutId = setTimeout(function() {
                        ztreeFilter(zTreeObj,_keywords); 
                    }, 500);
                }
            }
        },
        /** 事件绑定 */
        eventBind: function () {
            $(document).on("click", ".tab-nav li", function () {
                $(this).addClass("active").siblings("li").removeClass("active");
                var index = $(this).attr("type");
                $(".tab-wrapper").eq(index-1).removeClass("hidden").siblings(".tab-wrapper").addClass("hidden");
            })
            // 实时分析tab切换
            $(document).on("click", "#timeType1 li:not('.active')", function () {
                $(this).addClass("active").siblings("li").removeClass("active");
                app.initChart1();
            }); 
            $(document).on("click", "#timeType2 li:not('.active')", function () {
                $(this).addClass("active").siblings("li").removeClass("active");
                app.initChart2();
            })
            $(document).on("click", "#timeType3 li:not('.active')", function () {
                $(this).addClass("active").siblings("li").removeClass("active");
                app.initChart3();
            })
            $(document).on("click", "#timeType4 li:not('.active')", function () {
                $(this).addClass("active").siblings("li").removeClass("active");
                app.initChart4();
            })
            window.onresize = function () {
                // getTime.resize();
            };
        },
        
    };
    return app;
});